package tt.lab.pmbok.controller;

import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import tt.lab.pmbok.dto.InoutDTO;
import tt.lab.pmbok.dto.ProcessDTO;
import tt.lab.pmbok.dto.ToolDTO;
import tt.lab.pmbok.model.Inout;
import tt.lab.pmbok.model.PmbokProcess;
import tt.lab.pmbok.model.ProcessInout;
import tt.lab.pmbok.model.ProcessTool;
import tt.lab.pmbok.model.Tool;
import tt.lab.pmbok.service.ProcessService;

@Controller
// 类似Struts的Action
public class ProcessController {
	/**/
	@Resource(name = "processService")
	// 获取applicationContext.xml中bean的id为loginService的，并注入
	private ProcessService processService; // 等价于spring传统注入方式写get和set方法，这样的好处是简洁工整，省去了不必要得代码

	@RequestMapping("/all")
	public void retrieveAll(Model model) {
		List<PmbokProcess> processes = processService.loadAll();

		model.addAttribute(processes);
	}

	@RequestMapping("/process/{id}")
	public void retrieve(@PathVariable int id, Model model) {
		PmbokProcess process = processService.load(id);
		ProcessDTO processDTO = new ProcessDTO(process.getId(), process.getName(),process.getPmbokId());
		for (ProcessTool processTool : process.getTools()) {
			Tool tool = processTool.getTool();
			ToolDTO toolDTO = new ToolDTO(tool.getId(), tool.getName());
			processDTO.addTool(toolDTO);
		}

		for(ProcessInout processInout: process.getIns()){
			Inout in = processInout.getInout();
			InoutDTO inputDTO = new InoutDTO(in.getId(),in.getName());
			processDTO.addInput(inputDTO);
		}
		
		for(ProcessInout processInout: process.getOuts()){
			Inout out = processInout.getInout();
			InoutDTO outputDTO = new InoutDTO(out.getId(),out.getName());
			processDTO.addOutput(outputDTO);
		}
		
		model.addAttribute("process", processDTO);
	}

	/**
	 * 普通的xml，json，等 对ignoreAcceptHeader有反应 对url的扩展名有效
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/user")
	@ResponseStatus(HttpStatus.CREATED)
	public String register(PmbokProcess user, Model model) {
		try {
			System.out.println(1);
			// PmbokProcessService.createUser(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "testa";// ContentNigotiation => ViewResolver =>　View
	}

	@RequestMapping("/user/fp/{email}")
	public String findPassword(@PathVariable String email, PmbokProcess user, Model model) {

		return "loginSuccess";
	}

	@RequestMapping("/user/login/{username}/{password}")
	public String login(@PathVariable String username, @PathVariable String password, PmbokProcess user, Model model) {
		// User userDB =userService.login(username, password);
		// if (userDB==null) {
		// return "loginError";
		// }
		// model.addAttribute(userDB);
		return "loginSuccess";
	}

	@RequestMapping("/user/update/{id}")
	// , method=RequestMethod.DELETE通过HTTP的Method来判断操作类型
	public void put(@PathVariable int id, PmbokProcess user, Model model) {
		// userService.updateUser(user);
		// model.addAttribute(user);
		// 无需返回任何view的逻辑名称
	}

	@RequestMapping("/user/delete/{id}")
	// , method=RequestMethod.DELETE通过HTTP的Method来判断操作类型
	public void delete(@PathVariable int id) {
		// userService.deleteUser(id);
		// 无需返回任何view的逻辑名称
	}

	// 通过DefaultAnnotationHandlerMapping将请求映射到Controller的方法
	@RequestMapping(value = "/**", method = RequestMethod.GET)
	public String dynamic(HttpServletRequest request, HttpServletResponse response, ModelMap model) {

		return "home";
	}

	@RequestMapping("test/login.do")
	// 请求url地址映射，类似Struts的action-mapping
	// @RequestParam(value="username")
	public String testLogin(String username, String password, HttpServletRequest request) {
		// @RequestParam是指请求url地址映射中必须含有的参数(除非属性required=false)
		// @RequestParam可简写为：@RequestParam("username")

		if (!"admin".equals(username) || !"admin".equals(password)) {
			return "home"; // 跳转页面路径（默认为转发），该路径不需要包含spring-servlet配置文件中配置的前缀和后缀
		}
		return "loginSuccess";
	}

	@RequestMapping("test/login.spr")
	// 请求url地址映射，类似Struts的action-mapping
	public String testLoginS(String username, String password, HttpServletRequest request) {
		// @RequestParam是指请求url地址映射中必须含有的参数(除非属性required=false)
		// @RequestParam可简写为：@RequestParam("username")

		if (!"admin".equals(username) || !"admin".equals(password)) {
			return "loginError"; // 跳转页面路径（默认为转发），该路径不需要包含spring-servlet配置文件中配置的前缀和后缀
		}
		return "loginSuccess";
	}

	@RequestMapping("/test/login2.do")
	// http://localhost:8080/SpringMVC/test/login2.do?username=admin&password=admin&age=12
	public ModelAndView testLogin2(String username, String password, int age) {
		// request和response不必非要出现在方法中，如果用不上的话可以去掉
		// 参数的名称是与页面控件的name相匹配，参数类型会自动被转换

		if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
			return new ModelAndView("loginError"); // 手动实例化ModelAndView完成跳转页面（转发），效果等同于上面的方法返回字符串
		}
		return new ModelAndView(new RedirectView("../index.jsp")); // 采用重定向方式跳转页面
		// 重定向还有一种简单写法
		// return new ModelAndView("redirect:../index.jsp");
	}

	@RequestMapping("/test/login3.do")
	public ModelAndView testLogin3(PmbokProcess user) {
		// 同样支持参数为表单对象，类似于Struts的ActionForm，User不需要任何配置，直接写即可
		// String username = user.getUsername();
		// String password = user.getPassword();
		// int age = user.getAge();
		//
		// if (!"admin".equals(username) || !"admin".equals(password) || age < 5) {
		// return new ModelAndView("loginError");
		// }
		return new ModelAndView("loginSuccess");
	}

	/**
	 * 返回对象 对ignoreAcceptHeader无反应， 对url的扩展名无效，只认accept类型
	 * 
	 * @param user
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/testrb")
	@ResponseStatus(HttpStatus.CREATED)
	// @ResponseBody表示需要convert
	public @ResponseBody
	PmbokProcess testrb(PmbokProcess user, Model model) {

		// user.setPassword("wd密码1236789");
		return user;
	}
}